package com.lxq.dataStructure.lineList;


public class lineList<T> {
    //数组容量capacity=data.length
    private T[] data;
    //数组中存放数据大小
    private int size;

    //有参构造函数
    public lineList(int capacity) {
        data = (T[]) new Object[capacity];
        size = 0;
    }
    //无参构造函数，初始容量capacity=10
    public lineList(){
        this(10);
    }

    public int getSize(){
        return size;
    }
    public int getCapacity(){
        return data.length;
    }
    public boolean isEmpty(){
        return size==0;
    }
    /*public void addLast(T t){
        if (size == data.length) {
            throw new IllegalArgumentException("AddLast failed.lineList is full");
        }
        data[size] = t;
        size++;
    }*/

    public void addLast(T t){
        add(size,t);
    }
    public void addFirst(T t){
        add(0,t);
    }
    public void add(int index, T t) {
        if(size == data.length){
            throw new IllegalArgumentException("Add failded. Array is full.");
        }
        if(index<0||index>size){
            throw new IllegalArgumentException("Add failded. requre index >= 0 and index <= size");
        }
        for (int i = size-1 ; i >= index ; i--){
            data[i+1]=data[i];
        }
        data[index] = t;
        size++;
    }
    public T get(int index){
        if(index<0){
            throw new IllegalArgumentException("Get failed. Index is illegal.");

        }
        return data[index];
    }
    public void set(int index,T t){
        if (index<0||index>=size){
            throw new IllegalArgumentException("Set failed. Index is illegal");

        }
        data[index]=t;

    }
    public boolean contains(T t){
        for (int i=0;i<size;i++){
            if (data[i]==t){
                return true;
            }
        }
        return false;
    }
    public int find(T t){
        for (int i=0;i<size;i++){
            if (data[i]==t){
                return i;
            }
        }
        return -1;
    }
    public T remove(int index){
        if(index<0||index>size){
            throw new IllegalArgumentException("Add failded. requre index >= 0 and index <= size");
        }
        T ret=data[index];
        for (int i=index+1;i<size;i++){
            data[i-1]=data[i];
        }
        size--;
        data[size]=null;
        return ret;
    }
    @Override
    public String toString(){
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("lineList:size=%d,capacity=%d\n",size,data.length));
        sb.append("[");
        for(int i=0;i<size;i++){
            sb.append(data[i]).append(",");
        }
        sb.replace(sb.length()-1, sb.length(), "]");
        return sb.toString();
    }
}
